package kit

import (
	"github.com/golang/protobuf/protoc-gen-go/generator"
	pb "github.com/golang/protobuf/protoc-gen-go/descriptor"
)

type zk struct {
	zkName generator.GoPackageName
}

const zkPath = "github.com/go-kit/kit/sd/zk"
const pathPath = "path"
func (z *zk) Name() string{
	return "zk"
}
func (z *zk) AddImport(g *grpc){
	z.zkName = g.gen.AddImport(zkPath)
	g.gen.AddImport(pathPath)
}

func (z *zk) GeneratorRegistClient(g *grpc,file *generator.FileDescriptor, service *pb.ServiceDescriptorProto, index int){
	origServName := service.GetName()
	fullServName := origServName
	if pkg := file.GetPackage(); pkg != "" {
		fullServName = pkg + "." + fullServName
	}
	servName := generator.CamelCase(origServName)

	g.P("func NewBalance",servName,"Client(registry []string,p string,l log.Logger,maxtry int,timeout time.Duration)  *balance",servName," {")
	g.P("c, _ := ",z.zkName,".NewClient(registry, l)")
	g.P("inst, _ := ",z.zkName,".NewInstancer(c, p, l)")

}
func (z *zk) GeneratorRegistServer(g *grpc,file *generator.FileDescriptor, service *pb.ServiceDescriptorProto, index int){
	origServName := service.GetName()
	fullServName := origServName
	if pkg := file.GetPackage(); pkg != "" {
		fullServName = pkg + "." + fullServName
	}
	servName := generator.CamelCase(origServName)

	g.P("func Run",servName,"Server(registry []string,node string,bind string,svraddr string,server ",servName,"Server,l log.Logger)  {")
	g.P("c,_ := ",z.zkName,".NewClient(registry,l)")
	g.P("d,n:= path.Split(node)")
	g.P("sv :=&",z.zkName,".Service{")
	g.P("Path :d,")
	g.P("Name :n,")
	g.P("Data :[]byte(svraddr),")
	g.P("}")
	g.P("reg := ",z.zkName,".NewRegistrar(c,*sv,l)")
	g.P("reg.Register()")
}

// Init is called once after data structures are built but before
// code generation begins.
//func (z *zk) Init(g *generator.Generator){
//
//}
//// Generate produces the code generated by the plugin for this file,
//// except for the imports, by calling the generator's methods P, In, and Out.
//func (z *zk) Generate(file *FileDescriptor){
//
//}
//// GenerateImports produces the import declarations for this file.
//// It is called after Generate.
//func (z *zk) GenerateImports(file *FileDescriptor){
//
//}